require("../../both/base.js")
require("./UserRegister.scss")
import "../../../actions/base.js"

function setCookie(name,value)
{
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

class UserRegister extends React.Component{
    constructor(props){
        super(props)

        this.state = {
            email : "",
            password : "",
            repeatedPwd : "",
            verifyCode : "",
            username : "",
            verifyDisable : false,
            buttonValue : "获取邮件验证码"
        }

        this.captchaed = false
    }

    componentDidMount(){
        var self = this

        var handler = function (captchaObj) {
            captchaObj.appendTo("#captcha");

            captchaObj.onReady(function () {});

            captchaObj.onSuccess(function(){

                var result = captchaObj.getValidate();

                // send validate email
                fetch("/education/email/validate",{
                    method: 'POST',
                    body:   JSON.stringify({
                        email : self.state.email,
                        geetest_challenge: result.geetest_challenge,
                        geetest_validate: result.geetest_validate,
                        geetest_seccode: result.geetest_seccode,
                    }),
                    headers: { 'Content-Type': 'application/json' },
                    credentials : "same-origin"
                })
                    .then(res => res.json())
                    .then(json => {

                        toastr.success("邮件发送成功")

                        var i = 60
                        var interval = setInterval(() => {
                            if(i == 0){
                                clearInterval(interval)

                                self.setState({
                                    buttonValue : "获取邮件验证码",
                                    verifyDisable : false
                                })

                                document.getElementById("verify_captcha").style.display = "none"
                                self.captchaed = false
                                captchaObj.reset()
                                return
                            }

                            self.setState({
                                buttonValue : `${i}秒后重发`,
                                verifyDisable : true
                            })

                            -- i

                        },1000,i)

                    }).catch(err => {
                    console.log(err)
                    toastr.error("后台错误或邮箱不可用")
                })
            })
        }

        fetch("/education/email/geecode",{
            method: "get",
            credentials : "same-origin"
        })
            .then(res => res.json())
            .then(json => {
                initGeetest({
                    gt: json.gt,
                    challenge: json.challenge,
                    new_captcha: json.new_captcha, // 用于宕机时表示是新验证码的宕机
                    offline: !json.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                    product: "float", // 产品形式，包括：float，popup
                    width: "100%"

                }, handler);
            }).catch(err => {
            console.log(err)
            toastr.error("后台错误")
        })
    }

    updateChange(name,e){
        var self = this
        var change = {}
        change[name] = e.target.value
        self.setState(change)
    }

    verifyEmail(){
        var self = this

        if(self.state.verifyDisable){
            return
        }

        var emailStr = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if(!self.state.email || !emailStr.test(self.state.email)){
            toastr.warning("邮箱格式不合法")
            return
        }

        if(! self.captchaed){
            self.captchaed = true

            document.getElementById("verify_captcha").style.display = "block"
        }
    }

    registerAndLogin(e){
        e.preventDefault()

        var self = this
        var emailStr = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        var email = self.state.email
        var password = self.state.password
        var username = self.state.username
        var verifyCode = self.state.verifyCode
        var repeatedPwd = self.state.repeatedPwd

        if(!email || !emailStr.test(email)
        ){
            toastr.warning("邮箱格式不正确")
            return
        }

        if(!password || password.length < 6 || password.length > 16){
            toastr.warning("只支持6-16位密码")
            return
        }

        if(password !== repeatedPwd){
            toastr.warning("密码不一致")
            return
        }

        if(!username){
            toastr.warning("用户名不可为空")
            return
        }

        if(!verifyCode){
            toastr.warning("请输入邮箱验证码")
            return
        }

        fetch("/education/user/register",{
            method: 'POST',
            body:   JSON.stringify({
                email,
                password,
                username,
                verifyCode
            }),
            headers: { 'Content-Type': 'application/json' },
            credentials : "same-origin"
        })
            .then(res => res.json())
            .then(json => {

                // error process
                if(json.response && json.response.status == 400){
                    var err = JSON.parse(json.response.text).error
                    if(err === "verifyCodeError"){
                        toastr.error("验证码错误或过期")
                    }else if(err === "usernameRepeat"){
                        toastr.error("该用户名已注册")
                    }else if(err === "userCreateError"){
                        toastr.error("未知错误，用户创建失败，请联系管理员")
                    }else if(err === "emailRepeat"){
                        toastr.error("邮箱已注册")
                    }

                    return
                }

                // success
                toastr.success("注册成功")
                setCookie("LoginToken",json.msg.LoginToken)
                location.href = "/"

            }).catch(err => {
                console.log(err)
                toastr.error("后台错误")
            })

    }

    render(){
        const verifyEmail = this.verifyEmail.bind(this)
        const registerAndLogin = this.registerAndLogin.bind(this)

        return (<div className="user_register_cr bln">
            <form className="form_register">
                <div className="title">
                    注册以成为大神
                </div>
                <div className="form_group">
                    <label >邮箱：</label>
                    <input type="text" className="input_common" value={this.state.email} onChange={this.updateChange.bind(this,"email")}/>
                </div>
                <div className="form_group">
                    <label htmlFor="">昵称：</label>
                    <input type="text" className="input_common" value={this.state.username} onChange={this.updateChange.bind(this,"username")}/>
                </div>
                <div className="form_group">
                    <label htmlFor="">密码：</label>
                    <input type="password" className="input_common" value={this.state.password} onChange={this.updateChange.bind(this,"password")}/>
                </div>
                <div className="form_group">
                    <label htmlFor="">重复密码：</label>
                    <input type="password" className="input_common" value={this.state.repeatedPwd} onChange={this.updateChange.bind(this,"repeatedPwd")}/>
                </div>
                <div className="form_group">
                    <label htmlFor="">验证码：</label>
                    <div className="captcha_cr">
                        <input type="text" className="input_small" value={this.state.verifyCode} onChange={this.updateChange.bind(this,"verifyCode")}/>
                        {/*<img src="/p_dist/images/captcha.jpg" className="captcha"/>*/}
                        <button className="send_email" type="button" onClick={verifyEmail} disabled={this.state.verifyDisable ? "disable" : null}>
                            {this.state.buttonValue}
                        </button>
                    </div>
                </div>
                <div id="verify_captcha" className="form_group">
                    <label style={{top : "8px"}}>完成验证：</label>
                    <div id="captcha" />
                </div>
                <div className="form_group">
                    <input type="submit" className="input_submit" value="注册并登录" onClick={registerAndLogin}/>
                </div>
            </form>
        </div>)
    }
}

export default UserRegister